<?php

namespace Liuhelong\LaravelAdmin\Wechat\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\DefaultDatetimeFormat;

class WechatOffiaccountQrcode extends Model
{
    use HasFactory,DefaultDatetimeFormat;
	
	protected $dates = [
		'expired_at'
	];
	protected $guarded = ['id'];
	
	
	protected static function booted()
    {
		$wechat = app('liuhelong_wechat_service');
		
        static::created(function ($qrcode) use($wechat) {
			if($qrcode->type=='temporary'){
			    if(!$qrcode->expired_at || $qrcode->expired_at->lt(now())){			        
			        throw new \Exception('过期时间必须有且大于当前时间');
			    }
			    if($qrcode->expired_at->gt(now()->addDays(30))){			        
			        throw new \Exception('过期时间不能超过30天');
			    }
			    $seconds = now()->diffInSeconds($qrcode->expired_at, false);
				$result = $wechat->handle('qrcode','temporary',[$qrcode->key,$seconds]);
				
			}else{
				$result = $wechat->handle('qrcode','forever',[$qrcode->key]);
			}
			$qrcode->update([
				'ticket'=>$result['ticket'],
				'url'=>$result['url'],
				'expired_at'=>$qrcode->type=='forever'?null:$qrcode->expired_at,
			]);
        });
    }
}
